import { existsSync, readFileSync, writeFileSync } from "fs";
import { basename, dirname, join } from "path";
import { createDirSync, removeDir } from "../utils/FileUtil";
import { PublishLaya2Base } from "./PublishLaya2Base";

export class WebPublish extends PublishLaya2Base {
    get projDir() { return "webgame" };
    get libJs() { return ""; }
    async createProject() {
        let toPath = this.mProjPath;
        if (existsSync(toPath)) {
            createDirSync(toPath);
            await this.doPack();
        } else {
            await this.copyDir(this.mTempProjPath, toPath);
            let projCfgPath = join(toPath, 'index.html');
            let fstr = readFileSync(projCfgPath).toString();
            fstr = fstr.replace('${PORJECT_NAME}', this.mProjectInfo.name);
            writeFileSync(projCfgPath, fstr);

            this.log('项目生成完毕 下一步可以开始打包游戏了');
            await this.doPack();
        }
    }


    async doPack() {
        await this.buildProject();
        this.packOver();
    }

    protected mWriteConfig() {
        writeFileSync(join(this.mProjPath, this.getConfigName()), "window.config = " + this.config + ";");
    }


    saveFile(fileUrl: string, toPath: string, data: any) {
        let dirName = fileUrl;
        let fileName = basename(fileUrl);
        if (fileUrl.indexOf('/') >= 0) {
            dirName = dirname(fileUrl);
        }
        let destPath = join(toPath, dirName);
        createDirSync(destPath, () => {
            writeFileSync(join(destPath, fileName), data);
        });
    }
}